package com.qunar.support.dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.junit.Test;

import com.qunar.support.util.DBHelper;

public class UserDao {
	private Connection con;

	/**
	 * 若验证通过，返回其uid
	 * @param username
	 * @param password
	 * @return
	 */
	public int validate(String username, String password) {
		try {
			con = DBHelper.getConnection();
			String query = "select Id from user where username=? and password=?";
			PreparedStatement pstmt = con.prepareStatement(query);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			ResultSet rs = pstmt.executeQuery();
			int uid = -1;
			while (rs.next()) {
				uid = rs.getInt(1);
			}
			System.out.println(getClass()+":"+uid);
			return uid;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

	/**
	 * 计算过期天数
	 * @param uid
	 * @return
	 */
	public int overdueDay(int uid){
		try{
			con = DBHelper.getConnection();
			String query="select modify_date from user where Id=?";
			PreparedStatement pstmt=con.prepareStatement(query);
			pstmt.setInt(1, uid);
			ResultSet rs=pstmt.executeQuery();
			Date date=null;
			while(rs.next()){
				date=rs.getDate(1);
			}
			long od=(date.getTime()-System.currentTimeMillis())/(24*60*60*1000);
			int result=(int) (od+30);
			System.out.println("过期天数为"+result);
			return result;
		}catch(Exception e){
			e.printStackTrace();
		}
		return 0;
	}
	@Test
	public void run() {
		System.out.println(validate("admin", "admin"));
	}
}
